package com.star.aries.utils.excel;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

public class EnumIntegerConverter implements Converter<Integer> {

  @Override
  public Class<?> supportJavaTypeKey() {
    return Integer.class;
  }

  @Override
  public CellDataTypeEnum supportExcelTypeKey() {
    return CellDataTypeEnum.STRING;
  }

  @SuppressWarnings("rawtypes")
  public Integer convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
      GlobalConfiguration globalConfiguration) throws Exception {
    Integer code = 0;
    String info = cellData.toString();
    Field field = contentProperty.getField();
    TargetEnum annotation = field.getDeclaredAnnotation(TargetEnum.class);
    Class<? extends EnumIntf<?>> clazz = annotation.targetEnum();

    Object[] enumConstants = clazz.getEnumConstants();
    Method getInfo = clazz.getMethod("getCaption");
    Method getCode = clazz.getMethod("getCode");
    for (Object enumConstant : enumConstants) {
      if (getInfo.invoke(enumConstant).equals(info)) {
        code = Integer.parseInt(getCode.invoke(enumConstant) + "");
        break;
      }
    }
    return code;
  }

  @Override
  public CellData<String> convertToExcelData(Integer value, ExcelContentProperty contentProperty,
      GlobalConfiguration globalConfiguration) throws Exception {
    String info = "";
    Field field = contentProperty.getField();
    TargetEnum annotation = field.getDeclaredAnnotation(TargetEnum.class);
    Class<? extends EnumIntf<?>> clazz = annotation.targetEnum();
    Object[] enumConstants = clazz.getEnumConstants();
    Method getInfo = clazz.getMethod("getCaption");
    Method getCode = clazz.getMethod("getCode");
    for (Object enumConstant : enumConstants) {
      if (Integer.parseInt(getCode.invoke(enumConstant) + "") == value.intValue()) {
        info = (String) getInfo.invoke(enumConstant);
        break;
      }
    }
    return new CellData<>(info);
  }
}
